'''
集合法：超时
from collections import deque

xx, yy = [1, 0, -1, 0], [0, -1, 0, 1]

def bfs():
    Q, S = deque([st]), set()
    while Q:
        x, y, p, s = Q.popleft()
        if (x, y, p) in S: continue
        if a[x][y] == 'P': p = 1
        S.add((x, y, p))
        if (x, y) == ed and p > 0: return s
        for i in range(4):
            tx, ty = x + xx[i], y + yy[i]
            if tx < 0 or ty < 0 or tx >= n or ty >= n or a[tx][ty] == '#': continue
            Q.append((tx, ty, p, s + 1))
    return -1

n, m = map(int, input().split())
a = [i for i in range(n)]
for i in a:
    a[i] = input()
    for j in range(m):
        if a[i][j] == 'S':
            st = (i, j, 0, 0)
        if a[i][j] == 'T':
            ed = (i, j)
print(bfs())
'''
'''
标记法：超时
from collections import deque

xx, yy = [1, 0, -1, 0], [0, -1, 0, 1]

def bfs():
    Q = deque([st])
    while Q:
        x, y, p, s = Q.popleft()
        if a[x][y] == 'P': p = 1
        if (x, y) == ed and p > 0: return s
        for i in range(4):
            tx, ty = x + xx[i], y + yy[i]
            if tx < 0 or ty < 0 or tx >= n or ty >= n: continue
            if a[tx][ty] == '#' or a_[tx][ty][p]: continue
            a_[tx][ty][p] = True
            Q.append((tx, ty, p, s + 1))
    return -1

n, m = map(int, input().split())
a = [i for i in range(n)]
a_ = [[[False, False] for j in range(m)] for i in range(n)]
for i in a:
    a[i] = input()
    for j in range(m):
        if a[i][j] == 'S':
            st = (i, j, 0, 0)
        if a[i][j] == 'T':
            ed = (i, j)
print(bfs())
'''
# -------------------------------------------------------------------------------

# 比赛环境为python3.8.6版本自带的IDLE，最好早点熟悉一下。。这个东西的提示时有时无

# 菜单栏最右边的Help的Python Docs 比赛时候也可以看，不过建议还是提前多了解了解，

# 比赛的时候至少知道在文档找什么能用的上。

# IDLE是下载Python时自带的，在按住win+s搜索IDLE就能搜到了。

# 然后点左上角的File可以创建新文件，然后按F5可以运行。
